package com.kfm.spring.controller;

import com.kfm.spring.model.Account;
import com.kfm.spring.model.User;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@CrossOrigin
public class HelloController {

    @RequestMapping
    public String index(){
        return "hello";
    }

    @RequestMapping(value = "/hello", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
    // 允许跨域
    @CrossOrigin(origins = "*", maxAge = 3600, methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
    public String hello(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "n", defaultValue = "默认") String name, Account account) {
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
        //        try {
//            // 解决中文乱码，这里只对post请求有效。放在第一行
//            request.setCharacterEncoding("UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            throw new RuntimeException(e);
//        }
        String rName = request.getParameter("name");
        System.out.println(name);
        System.out.println(rName);
        // 逻辑视图名
        return "hello";
    }

    @RequestMapping(value = "/hello2", method = RequestMethod.POST)
    public String helloPut(HttpServletRequest request) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String name = request.getParameter("name");
        System.out.println(name);
        // 逻辑视图名
        return "hello";
    }

    @RequestMapping(value = "/hello3")
    public String hello3(@DateTimeFormat(pattern = "yyyy-MM-dd") Date date){
        System.out.println(date);
        return "hello";
    }


    @RequestMapping("/hello4")
    public String hello4(User user) throws Exception {
        return "hello";
    }


    // TODO(1) 如何将多个account的name和money传递到后台 ？？？
    // 1. account.name account.money
    // 2. account[0].name account[0].money
    // 3. account[1].name account[1].money
    @RequestMapping("/hello5")
    public String hello5(List<Account> accounts) throws Exception {
        return "hello";
    }
}
